package cn.cagurzhan.filter;

import cn.cagurzhan.common.constant.HttpStatus;
import cn.cagurzhan.common.exception.ServiceException;
import cn.cagurzhan.domain.R;
import cn.cagurzhan.utils.AppJwtUtil;
import cn.cagurzhan.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 鉴权过滤器
 * @author AjaxZhan
 */
public class AuthenticationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        // 放行转发URL
        String uri = request.getRequestURI();
        if(uri.contains("/collect") || uri.contains("ask_vis") || uri.contains("yuyin")){
            filterChain.doFilter(request,response);
            return;
        }

        // 从请求中提取JWT并进行验证
        String jwt = request.getHeader("token");
        // jwt 为空
        if(StringUtils.isEmpty(jwt)){
            response.setStatus(HttpStatus.UNAUTHORIZED);
            String msg = JSON.toJSONString(R.fail(HttpStatus.UNAUTHORIZED, "校验失败，请携带token请求"));
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(msg);
            response.flushBuffer();
            return;
        }
        // 验证token
        Claims claimsBody = AppJwtUtil.getClaimsBody(jwt);
        int res = AppJwtUtil.verifyToken(claimsBody);
        if(res == 1 || res == 2){
            // 过期
            response.setStatus(HttpStatus.UNAUTHORIZED);
            String msg = JSON.toJSONString(R.fail(HttpStatus.UNAUTHORIZED, "校验失败，请携带token请求"));
            response.setCharacterEncoding("utf-8");
            response.getWriter().write(msg);
            response.flushBuffer();
            return;
        }
        // 放行
        filterChain.doFilter(request, response);
    }
}
